layui.use(['jquery', 'laydate', 'layer', 'form', 'table', 'util', 'configs'], function () {
    var $ = layui.jquery,
        laydate = layui.laydate,
        layer = layui.layer,
        form = layui.form,
        table = layui.table,
        util = layui.util,
        config = layui.configs;
    // 维护类型
    let mType = {
        1: '马达',
        2: '传感器',
        3: '采集模块',
        4: '服务器',
        5: '日常维护',
        6: '其他',
    };
    let searchParams = null;
    initAll();

    function initAll() {
        // 初始化筛选条件
        $('.maintain-type').append(typeHtml());  // 维护类型select
        form.render();
        initDate('startDate', new Date(new Date().toLocaleDateString()));
        initDate('endDate');
        let timer = null;
        if(timer){
            clearTimeout(timer);
        }
        timer = setTimeout(function () {
            $(".searchBtn").click();
        },0)
    }

    //查询
    $(".searchBtn").click(function () {
        form.on('submit(search)', function (data) {
            searchParams = data.field;
            getTableData(searchParams);
            return false;
        });
    });

    // 返回值： 维护类型的 option -html
    function typeHtml() {
        let opt = '';
        for(let k in mType){
            opt += `<option value="${k}">${mType[k]}</option>`
        }
        return opt;
    }

    function initDate(elm, value) {
        laydate.render({
            elem: `#${elm}`,
            value: value || new Date(),
            format: 'yyyy-MM-dd HH:mm:ss',
            type: 'datetime',
            trigger: 'click',
            max: formatDate()
        });
    }

    function getTableData(param) {
        $.ajax({
            url: config.motorBaseUrl + "",
            type: "post",
            datatype: "json",
            data: param,
            success: function (result) {
                if (result.stateCode == 0) {
                    let data = result.data;
                    // let data = [
                    //     {sn:1, type:1 ,recDate:'2020-11-24 10:12:12',staff:'张三',content:'马达更换'},
                    //     {sn:2, type:2,recDate:'2020-11-25 10:12:12',staff:'李四',content:'传感器更换'},
                    //     {sn:3, type:3,recDate:'2020-11-26 10:12:12',staff:'王五',content:'采集模块更换'},
                    //     {sn:4, type:4,recDate:'2020-11-24 10:12:12',staff:'甲',content:'服务器更换'},
                    //     {sn:5, type:5,recDate:'2020-11-25 10:12:12',staff:'乙',content:'日常维护'},
                    //     {sn:6, type:6,recDate:'2020-11-26 10:12:12',staff:'丙',content:''},
                    // ];
                    renderTable(data);
                } else {
                    layer.msg(result.stateMsg);
                }
            }
        })
    }

    //渲染表格
    function renderTable(data) {
        table.render({
            elem: '.maintainTable'
            , id: 'area-table'
            , data: data
            , cols: [[
                {field: 'sn', title: '序号'}
                , {field: 'type', title: '维护类型', templet: function(d){ return mType[d.type] }}
                , {field: 'recDate', title: '维护时间'}
                , {field: 'content', title: '维护内容'}
                , {field: 'staff', title: '维护人'}
                , {fixed: 'right', title: '操作', width: 100, align: 'center', toolbar: '#rowOperate'}
            ]]
            , page: {
                layout: ['prev', 'page', 'next', 'count', 'skip', 'limit']
                , groups: 1
                , first: false
                , last: false
                , limits: [10, 20, 50, 100, 500]
            }
            , limit: 10
            , loading: true
        });
    }

    //新增
    $('.addBtn').click(function(){
        var layerIdx = layer.open({
            type: 1,
            title: "新增",
            closeBtn: 1,
            anim: 0,
            area: 'auto',
            content: $('#layerRec').html(),
            success: function(layero){
                layero.find('.maintain-type').append(typeHtml());
                form.render();
                initDate('recDate');
            }
        });
        form.on('submit(recForm)', function (res) {
            addRec(res.field,layerIdx);
            return false;
        });
        $(".layerRec button[type='cancel']").click(function () {
            layer.close(layerIdx);
            return false;
        });
    });

    function addRec(dataObj,layerIdx) {
        $.ajax({
            url: config.motorBaseUrl + "",
            type: "post",
            datatype: "json",
            data: dataObj,
            success: function (result) {
                if (result.stateCode == 0) {
                    layer.close(layerIdx);
                    getTableData(searchParams);
                } else {
                    layer.alert(result.stateMsg);
                }
            }
        })
    }

    // 编辑、删除
    table.on('tool(maintainTable)', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;
        if (layEvent === 'del') { //删除
            layer.confirm('确定删除吗？', function (index) {
                deleteRec(obj);
                layer.close(index);
            });
        } else if (layEvent === 'edit') { //编辑
            var layerIdx = layer.open({
                type: 1,
                title: "编辑",
                closeBtn: 1,
                anim: 0,
                area: 'auto',
                content: $('#layerRec').html(),
                success: function(layero){
                    layero.find('.maintain-type').append(typeHtml());
                    form.render();
                    initDate('recDate', data.recDate);
                }
            });
            form.val("recForm", data);
            form.on('submit(recForm)', function (res) {
                let updParam = Object.assign({},res.field);
                updParam.sn = obj.data.sn;
                updateRec(obj, updParam,layerIdx);
                layer.close(layerIdx);
                return false;
            });
            $(".layerRec button[type='cancel']").click(function () {
                layer.close(layerIdx);
                return false;
            });
        }
    });

    /* obj 原值
    * data 改后新值
    * layerIdx 弹窗索引
    * */
    function updateRec(obj, param,layerIdx) {
        $.ajax({
            url: config.motorBaseUrl + "",
            type: "post",
            datatype: "json",
            data: param,
            success: function (result) {
                if (result.stateCode == 0) {
                    refreshTable("update", obj, param);
                    layer.close(layerIdx);
                } else {
                    layer.alert(result.stateMsg);
                }
            }
        })
    };

    function deleteRec(obj) {
        $.ajax({
            url: config.motorBaseUrl + "",
            type: "post",
            datatype: "json",
            data: obj.data,
            success: function (result) {
                if (result.stateCode == 0) {
                    refreshTable('delete', obj);
                } else {
                    layer.alert(result.stateMsg);
                }
            }
        })
    };

    //清空--赋初始值
    $('.clearBtn').click(function(){
        form.val('parameter',{
            type: 1,
            staff: ''
        });
        $('#startDate').val(util.toDateString(new Date().toLocaleDateString()));
        $('#endDate').val(util.toDateString(new Date()));
    });

    // 编辑删除后，更新对应缓存，减少请求
    function refreshTable(type, obj, data) {
        if (type == "update") {
            obj.update(data); //同步更新缓存对应的值
        } else if (type == "delete") {
            obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
        }
    }
});
